const md5 = require('./md5.js');
let baseUrl = 'https://txxzdata.tingxiangzu.com'

function isNumber(obj) {
	return typeof obj === 'number' && !isNaN(obj)
}

export function uploadImg(callback) {
	uni.chooseImage({
		success: (res) => {
			const imgUrl = res.tempFilePaths[0];
			const secretKey = 'sdksdksdcfsd'
			const data = {
				timeStamp: new Date().getTime() + ''
			}
			let crypt = md5.hexMD5(JSON.stringify(data) + secretKey);
			uni.uploadFile({
				url: baseUrl + '/Alipay/upload',
				filePath: imgUrl,
				name: 'file',
				header: {
					'Content-Type': 'multipart/form-data',
					'crypt': crypt
				},
				formData: {
					'user': 'test'
				},
				success: res => {
					const result = JSON.parse(res.data);
					if (result.status == 200) {
						return callback(result.data.image);
					} else {
						uni.showToast({
							icon: 'fail',
							title: '上传成功',
							duration: 1000,
						});
						return callback(false);
					}
				},
				fail: function(res) {
					uni.showToast({
						icon: 'fail',
						title: '上传图片失败',
						duration: 1000,
					});
					return callback(false);
				},
			});
		}
	})
}

export function request(config) {
	const secretKey = 'sdksdksdcfsd'
	const timeStamp = new Date().getTime() + '';
	// 解构赋值
	let {
		url = '', data = {
			timeStamp
		}, method = 'POST'
	} = {
		...config
	};
	for (let key in data) {
		if (isNumber(data[key])) {
			data[key] += '';
		}
	}
	let crypt = md5.hexMD5(JSON.stringify(data) + secretKey);
	const token = uni.getStorageSync('token')
	let header = token ? {
		token,
		crypt
	} : {
		crypt
	};
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			method: method,
			data: {
				...data
			},
			header: {
				...header
			},
			success: (res) => {
				const app = getApp();
				if (res.data && res.data.status === 200) {
					resolve(res.data.data)
				} else if (res.data && res.data.status === 300) { //未授权
					if (token) {
						uni.removeStorageSync('userInfo')
						uni.removeStorageSync('token')
						getApp().globalData.userInfo={}
						// app.getAuthBase()
						console.log(res);
						uni.showToast({
							icon:"error",
							title:res.data.msg,
							duration:5000
						});
						setTimeout(function(){
							uni.reLaunch({
								url:'/pages/my/my'
							})
						},3000)
					
					} else {
						// app.getAuthUser()
					}
				} else {
					uni.showToast({
						icon:'error',
						title: res.data.msg,
						duration: 5000
					});
					reject(res)
				}
			},
			fail: (err) => {
				reject(err)
			},
			// complete: () => {
			//   setTimeout(() => {
			//     my.hideLoading();
			//   }, 400)
			// }
		});
	})
}